package com.stn.zjx.givingtreasure.activity.set;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.text.format.Formatter;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.came.viewbguilib.ButtonBgUi;
import com.google.gson.Gson;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.stn.zjx.givingtreasure.R;
import com.stn.zjx.givingtreasure.glide.GlideImageGetter;
import com.stn.zjx.givingtreasure.glide.UrlDrawable;
import com.stn.zjx.givingtreasure.activity.web.GenericWebActivity;
import com.stn.zjx.givingtreasure.base.BaseActivity;
import com.stn.zjx.givingtreasure.constants.StnConstants;
import com.stn.zjx.givingtreasure.domain.UpdateVersionDomain;
import com.stn.zjx.givingtreasure.event.NetWorkEvent;
import com.stn.zjx.givingtreasure.net.BaseApi;
import com.stn.zjx.givingtreasure.net.impl.CheckVersionNetImpl;
import com.stn.zjx.givingtreasure.service.AppUpdateService;
import com.stn.zjx.givingtreasure.utils.ToolsUtils;
import com.vondear.rxtools.RxActivityTool;
import com.vondear.rxtools.RxAppTool;
import com.vondear.rxtools.RxImageTool;
import com.vondear.rxtools.RxSPTool;
import com.vondear.rxtools.view.RxQRCode;
import com.zzhoujay.richtext.ImageHolder;
import com.zzhoujay.richtext.RichText;
import com.zzhoujay.richtext.RichTextConfig;
import com.zzhoujay.richtext.callback.BitmapStream;
import com.zzhoujay.richtext.callback.ImageGetter;
import com.zzhoujay.richtext.callback.ImageLoadNotify;
import com.zzhoujay.richtext.callback.OnUrlClickListener;
import com.zzhoujay.richtext.ig.DefaultImageGetter;
import com.zzhoujay.richtext.ig.ImageDownloader;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.util.Objects;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

public class AboutUsActivity extends BaseActivity {
    private static final int PRC_PHOTO_PICKER = 1010;
    @BindView(R.id.back_bt)
    RelativeLayout backBt;
    @BindView(R.id.action_title)
    TextView actionTitle;
    @BindView(R.id.web_title)
    TextView webTitle;
    @BindView(R.id.action_add_bt)
    RelativeLayout actionAddBt;
    @BindView(R.id.action_refresh)
    RelativeLayout actionRefresh;
    @BindView(R.id.exit)
    RelativeLayout exit;
    @BindView(R.id.sure_bt)
    TextView sureBt;
    @BindView(R.id.share_bt)
    RelativeLayout shareBt;
    @BindView(R.id.version_tv)
    TextView versionTv;
    @BindView(R.id.er_iv)
    ImageView erIv;
    @BindView(R.id.check_update)
    RelativeLayout checkUpdate;
    @BindView(R.id.rootView)
    LinearLayout rootView;
    @BindView(R.id.update_tip_dot)
    View updateTipDot;
    private String update_url = "";
    public Dialog update_dialog;
    private TextView vs_title;
    private TextView vs_size;
    private TextView vs_info;
    private ButtonBgUi vs_ok;
    private TextView tv_ignore;


    @Override
    public void networkStatus(NetWorkEvent netWorkEvent) {

    }

    @SuppressLint("SetTextI18n")
    @Override
    public void initComponent() {
        actionTitle.setText(getString(R.string.about_us));
        shareBt.setVisibility(View.VISIBLE);
        versionTv.setText("For Android Version " + RxAppTool.getAppVersionName(this));
        CheckVersionNetImpl.get_version(0, "get_version",
                new StringCallback() {
                    @SuppressLint("SetTextI18n")
                    @Override
                    public void onSuccess(Response<String> response) {
                        if (response.isSuccessful() && !isFinishing()) {
                            UpdateVersionDomain domain = new Gson().fromJson(response.body(), UpdateVersionDomain.class);
                            switch (domain.getStatus()) {
                                case BaseApi.REQUEST_SUCCESS_CODE:
                                    if (domain.getData() != null) {
                                        erIv.setImageBitmap(RxQRCode.creatQRCode(domain.getData().getAppUrl()));
                                        int local_code = RxAppTool.getAppVersionCode(getApplicationContext());
                                        if (local_code < domain.getData().getAppCode()) {
                                            updateTipDot.setVisibility(View.VISIBLE);

                                        }else{
                                            updateTipDot.setVisibility(View.GONE);
                                        }
                                    }else{
                                        updateTipDot.setVisibility(View.GONE);
                                    }
                                    break;
                            }
                        }

                    }
                });


    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_system_about_us);
        ButterKnife.bind(this);
        initComponent();
        initUpdateDialaog();
    }

    public void initUpdateDialaog() {
        update_dialog = new Dialog(this);
        Objects.requireNonNull(update_dialog.getWindow()).setBackgroundDrawable(new ColorDrawable(ActivityCompat.getColor(this, R.color.translucent)));
        update_dialog.setContentView(R.layout.dialog_update_version);
        update_dialog.setCanceledOnTouchOutside(false);
        View ll_top = update_dialog.findViewById(R.id.ll_top);
        vs_title = update_dialog.findViewById(R.id.tv_title);
        vs_size = update_dialog.findViewById(R.id.version_size);
        vs_info = update_dialog.findViewById(R.id.tv_update_info);
        vs_ok = update_dialog.findViewById(R.id.btn_ok);
        vs_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String[] perms = {Manifest.permission.CAMERA,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                };
                //是否有以上权限
                if (EasyPermissions.hasPermissions(AboutUsActivity.this, perms)) {
                    Intent start = new Intent(AboutUsActivity.this, AppUpdateService.class);
                    start.putExtra("download_url", update_url);
                    startService(start);
                    update_dialog.dismiss();
                } else {
                    //发起请求权限
                    // Do not have permissions, request them now
                    EasyPermissions.requestPermissions(AboutUsActivity.this, getString(R.string.request_perssion_desc),
                            100, perms);
                }


            }
        });
        tv_ignore = update_dialog.findViewById(R.id.tv_ignore);
        tv_ignore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                RxSPTool.putBoolean(getApplicationContext(), StnConstants.isCloseCehckVersion, true);
                update_dialog.dismiss();
            }
        });
        update_dialog.findViewById(R.id.iv_close)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        update_dialog.dismiss();
                    }
                });

        String[] perms = {Manifest.permission.CAMERA,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_NETWORK_STATE
        };
        //是否有以上权限
        if (EasyPermissions.hasPermissions(AboutUsActivity.this, perms)) {

        } else {
            //发起请求权限
            // Do not have permissions, request them now
            EasyPermissions.requestPermissions(AboutUsActivity.this, getString(R.string.request_perssion_desc),
                    100, perms);
        }


    }

    @OnClick({R.id.back_bt, R.id.check_update, R.id.share_bt})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_bt:
                finish();
                break;
            case R.id.check_update:
                checkVersion();
                break;
            case R.id.share_bt:

                Bitmap bitmap = ToolsUtils.getBitmapByView(rootView);
                savetoImg(bitmap);
                break;

        }
    }

    @AfterPermissionGranted(PRC_PHOTO_PICKER)
    public void savetoImg(Bitmap bitmap) {
        String[] perms = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
        if (EasyPermissions.hasPermissions(this, perms)) {
            showLoading();
            // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话就没有拍照功能
            File file = new File(Environment.getExternalStorageDirectory().getPath(), getString(R.string.app_name));
            if (!file.exists()) {   //判断文件夹是否存在，不存在则创建
                file.mkdirs();
            }
            String fileName = "";
            fileName = UUID.randomUUID().toString().substring(0, 4) + ".jpg";
            String com_file = file.getPath() + "/" + fileName;
            boolean isSuccess = RxImageTool.save(bitmap, com_file, Bitmap.CompressFormat.JPEG);
            if (isSuccess) {
                // 把文件插入到系统图库
                try {
                    String s = MediaStore.Images.Media.insertImage(getContentResolver(), com_file, fileName, "分享图片");

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + com_file));
                // 通知图库更新
                sendBroadcast(intent);

                ToolsUtils.shareImage(this, new File(com_file));
            } else {
                showToast("save error");
            }
            dissmissLoading();
        } else {
            EasyPermissions.requestPermissions(this, getString(R.string.request_perssion_desc), PRC_PHOTO_PICKER, perms);
        }
    }


    public void checkVersion() {
        CheckVersionNetImpl.get_version(0, "get_version",
                new StringCallback() {
                    @SuppressLint("SetTextI18n")
                    @Override
                    public void onSuccess(Response<String> response) {
                        if (response.isSuccessful() && !isFinishing()) {
                            UpdateVersionDomain domain = new Gson().fromJson(response.body(), UpdateVersionDomain.class);
                            switch (domain.getStatus()) {
                                case BaseApi.REQUEST_SUCCESS_CODE:
                                    if (domain.getData() != null) {
                                        int local_code = RxAppTool.getAppVersionCode(getApplicationContext());
                                        if (local_code < domain.getData().getAppCode()) {
                                            String size = Formatter.formatFileSize(getApplicationContext(), domain.getData().getAppSize());
                                            vs_title.setText(getString(R.string.upgradeto) + "" + domain.getData().getAppVersion() + getString(R.string.version) + "?");
                                            vs_size.setText(getString(R.string.new_version_size) + ":" + size);
                                            // 加载富文本
                                            RichText.from(domain.getData().getAppDescription())

                                                    .imageGetter(new GlideImageGetter(AboutUsActivity.this))
                                                    .bind(AboutUsActivity.this)
                                                    .urlClick(new OnUrlClickListener() {
                                                        @Override
                                                        public boolean urlClicked(String url) {
                                                            Bundle bundle = new Bundle();
                                                            bundle.putString("url", url);
                                                            RxActivityTool.skipActivity(getApplicationContext(), GenericWebActivity.class, bundle);
                                                            return true;
                                                        }
                                                    }).into(vs_info);
                                            update_url = domain.getData().getAppUrl();
                                            update_dialog.show();
                                        }else{
                                           showToast(getString(R.string.now_version_new));
                                        }

                                    }
                                    break;
                            }
                        }

                    }
                });


    }


}
